package com.nky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nky.controller.dto.UserDTO;
import com.nky.mapper.RoleMenuMapper;
import com.nky.mapper.UserMapper;
import com.nky.pojo.Menu;
import com.nky.pojo.User;
import com.nky.service.IUserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Resource
    private MenuServiceImpl menuService;

    public UserDTO loginAccount(UserDTO userDTO) {
        User user = getUserInfo(userDTO);
//        if (user == null) {
//            // TODO:抛出异常 throw new ServiceException(Constants.CODE_600,"账号或者密码错误");
//        }
        Integer roleId = user.getRoleId();
        Integer institutionId = user.getInstitutionId();
//
        // 根据用户的角色和机构设置菜单列表
        List<Menu> roleMenus = getRoleMenus(roleId, institutionId);
        userDTO.setMenus(roleMenus);

        return userDTO;
    }

    /**
     * 根据UserDTO查询User表中的用户数据
     *
     * @param userDTO 前端传来的用户数据对象
     * @return User表中的用户数据
     */
    public User getUserInfo(UserDTO userDTO) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getName, userDTO.getUsername());
        queryWrapper.eq(User::getPassword, userDTO.getPassword());
        return getOne(queryWrapper);
    }

    /**
     * 根据角色id和单位id查询该角色拥有权限的菜单列表（包括子菜单结构）
     *
     * @param roleId        角色id
     * @param institutionId 单位id
     * @return 菜单列表
     */
    public List<Menu> getRoleMenus(Integer roleId, Integer institutionId) {
        //查出当前角色的所有菜单ID
        List<Integer> menuIds = roleMenuMapper.selectByRoleId(roleId, institutionId);
        // 查出系统所有菜单
        List<Menu> menus = menuService.findMenus("");
        // 新建筛选后的菜单列表
        List<Menu> roleMenus = new ArrayList<>();
        // 筛选当前用户角色的菜单
        for (Menu menu : menus) {
            if (menuIds.contains(menu.getMenuId())) {
                roleMenus.add(menu);
            }
            List<Menu> children = menu.getChildren();
            // 移除children里面不在menuIds集合中的元素
            children.removeIf(child -> !menuIds.contains(child.getMenuId()));
        }
        return roleMenus;
    }
}
